import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.AirlineReservationServiceProxy;
import bean.Journey;
import bean.Person;
import bean.ReservationDetails;
import constants.AirlineReservationServiceConstants;


public class MakeReservationServlet extends HttpServlet{
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		AirlineReservationServiceProxy proxy = new AirlineReservationServiceProxy(
				AirlineReservationServiceConstants.SERVICE_URL);
		
		HttpSession session = req.getSession();
		
		List<Journey> lstJourney = (List<Journey>)session.getAttribute("journeyDetails");
		
		Person person = (Person) session.getAttribute("user");
		
		int numPassengers = Integer.parseInt((String)session.getAttribute("numTravelers"));
		
		ReservationDetails[] arrReservation = new ReservationDetails[numPassengers];
		for(int i=1; i<=numPassengers; i++ ){
			
			String firstName = req.getParameter("firstName"+i);
			String lastName = req.getParameter("lastName"+i);
			int age = Integer.parseInt(req.getParameter("age"+i));
			arrReservation[i-1] = new ReservationDetails();
			arrReservation[i-1].setAge(age);
			arrReservation[i-1].setFirstName(firstName);
			arrReservation[i-1].setLastName(lastName);	
			
			
		}
		Journey[] arrJourney = new Journey[lstJourney.size()];
		for(Journey obj : lstJourney){
			obj.setReservationDetails(arrReservation);			
		}
		
		req.setAttribute("issueTicket", "issueTicket");
		
		arrJourney = proxy.reserve(numPassengers, lstJourney.toArray(arrJourney), person.getId());
		
		if(arrJourney!=null && arrJourney.length!=0){
			if(arrJourney[0].getConfirmationNumber()!=0){
				lstJourney.clear();
				for(Journey j : arrJourney){
					lstJourney.add(j);
				}
				req.setAttribute("reservationConfirmation", lstJourney);
				
			}else{
				req.setAttribute("error", "There has been an error while processing your request. Please try again.");
			}
		}else{
			req.setAttribute("error", "There has been an error while processing your request. Please try again.");			
		}
		
		
		req.getRequestDispatcher("customer/start.jsp").forward(req,resp);
		
		
		
	}

}
